package com.zzjson.design.proxy.my.custom.proxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2018 rollBall team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : 代码生成，编译，重新loader到jvm中</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2018年12月01日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class MyClassLoader extends ClassLoader {
    private File baseDir;

    public MyClassLoader() {
        String baseDir = MyClassLoader.class.getResource("").getPath();
        this.baseDir = new File(baseDir);
    }

    @Override

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            if (baseDir != null) {
                File f = new File(baseDir, name.replaceAll("\\.", "/") + ".class");
                in = new FileInputStream(f);
                out = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int len;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                return defineClass(className, out.toByteArray(), 0, out.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}